package com.kinghunt.misp.web.controller.userx;

import com.kinghunt.misp.common.constant.SystemConstant;
import com.kinghunt.misp.common.dto.common.Tree;
import com.kinghunt.misp.common.dto.userx.OrganizationDTO;
import com.kinghunt.misp.common.param.userx.OrganizationParam;
import com.kinghunt.misp.service.api.userx.OrganizationReadService;
import com.kinghunt.misp.service.api.userx.OrganizationWriteService;
import com.bygoodtech.kings.common.dto.ApiResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import java.util.Objects;


/**
 * 组织管理控制器
 *
 * @author jiangtao
 */
@RestController
@RequestMapping("/api/userx/organization/")
public class OrganizationController {
    @Autowired
    OrganizationReadService organizationReadService;
    @Autowired
    OrganizationWriteService organizationWriteService;

    /**
     * 根据ID查询机构信息
     *
     * @param id 机构ID
     * @return 机构信息
     */
    @GetMapping("getOrganizationInfoById")
    public ApiResult<OrganizationDTO> getOrganizationInfoById(Long id) {
        return organizationReadService.getOrganizationById(id);
    }

    /**
     * 查询应用下所有机构树
     *
     * @param appCode 应用code
     * @return 机构树
     */
    @GetMapping("getAllOrganizationInfos")
    public ApiResult<Tree<OrganizationDTO>> getOrganizationTree(String appCode) {
        if (StringUtils.isEmpty(appCode)) {
            appCode = SystemConstant.SYSTEM_CODE;
        }
        return organizationReadService.getOrganizationTree(appCode);
    }

    /**
     * 新增机构
     *
     * @param organizationParam 新增机构信息
     * @return 新增机构ID
     */
    @PostMapping(value = "addOrganization", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ApiResult<Long> addOrganization(@RequestBody OrganizationParam organizationParam) {
        if (Objects.isNull(organizationParam)
                || Objects.isNull(organizationParam.getParentId())
                || StringUtils.isEmpty(organizationParam.getName())) {
            return ApiResult.failOfMessage("创建失败，参数错误");
        }
        return organizationWriteService.addOrganization(organizationParam);
    }

    /**
     * 更新机构信息
     *
     * @param organizationParam 更新机构信息
     * @return 是否成功
     */
    @PostMapping(value = "updateOrganization", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ApiResult<Boolean> updateOrganization(@RequestBody OrganizationParam organizationParam) {
        return organizationWriteService.updateOrganizationInfo(organizationParam);
    }

    /**
     * 删除机构
     *
     * @param id 机构ID
     * @return 是否成功
     */
    @GetMapping("deleteOrganization")
    public ApiResult<Boolean> deleteOrganization(Long id) {
        return organizationWriteService.deleteOrganization(id);
    }
}
